<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
      <div class="text-center">
        <h2 class="mt-6 text-3xl font-extrabold text-gray-900">{{ t('重置密码') }}</h2>
        <p class="mt-2 text-sm text-gray-600">{{ t('请输入您的新密码') }}</p>
      </div>

      <el-form
          ref="resetForm"
          :model="form"
          :rules="rules"
          class="mt-8 space-y-6"
          @submit.prevent="handleResetPassword"
      >
        <el-form-item prop="email">
          <el-input
              v-model="form.email"
              :placeholder="t('请输入注册邮箱')"
              prefix-icon="el-icon-message"/>
        </el-form-item>

        <el-form-item prop="code">
          <div class="flex space-x-2">
            <el-input
                v-model="form.code"
                :placeholder="t('请输入验证码')"
                prefix-icon="el-icon-lock"
            />
            <el-button
                :disabled="codeDisabled"
                @click="sendVerificationCode"
            >
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              :placeholder="t('请输入新密码')"
              prefix-icon="el-icon-lock"
              show-password/>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              :placeholder="t('请确认新密码')"
              prefix-icon="el-icon-lock"
              show-password/>
        </el-form-item>

        <div>
          <el-button
              type="primary"
              native-type="submit"
              class="w-full"
              :loading="loading">
            {{ t('重置密码') }}
          </el-button>
        </div>
      </el-form>

      <div class="text-center">
        <el-link type="primary" :underline="false" @click="goToLogin">
          {{ t('返回登录') }}
        </el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sendResetCode, resetPassword } from '@/api/auth'
import {login} from "@/router/index.js";
import {useI18n} from "vue-i18n";

const {t} = useI18n()
const router = useRouter()

const resetForm = ref(null)
const loading = ref(true)
const codeDisabled = ref(false)
const codeButtonText = ref(t('获取验证码'))
let countdown = 60

const form = ref({
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('请再次输入密码')))
  } else if (value !== form.value.password) {
    callback(new Error(t('两次输入密码不一致!')))
  } else {
    callback()
  }
}

const rules = ref({
  email: [
    { required: true, message: t('请输入邮箱'), trigger: 'blur' },
    { type: 'email', message: t('请输入正确的邮箱地址'), trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: t('请输入验证码'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('请输入密码'), trigger: 'blur' },
    { min: 6, max: 20, message: t('长度在 6 到 20 个字符'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ]
})

// 发送验证码
const sendVerificationCode = async () => {
  try {
    await resetForm.value.validateField('email')

    await sendResetCode(form.value.email)
    ElMessage.success(t('验证码已发送'))

    // 开始倒计时
    codeDisabled.value = true
    const timer = setInterval(() => {
      countdown--
      codeButtonText.value = `${countdown}${t('秒后重新获取')}`

      if (countdown <= 0) {
        clearInterval(timer)
        codeDisabled.value = false
        codeButtonText.value = t('获取验证码')
        countdown = 60
      }
    }, 1000)
  } catch (error) {
    if (error.fields) {
      ElMessage.warning(t('请检查邮箱输入'))
    } else {
      ElMessage.error(error.message || t('发送验证码失败'))
    }
  }
}

// 重置密码
const handleResetPassword = async () => {
  try {
    await resetForm.value.validate()
    loading.value = true

    await resetPassword({
      email: form.value.email,
      code: form.value.code,
      newPassword: form.value.password
    })

    ElMessage.success(t('密码重置成功'))
    goToLogin()
  } catch (error) {
    if (error.fields) {
      ElMessage.warning(t('请检查表单填写'))
    } else {
      ElMessage.error(error.message || t('重置密码失败'))
    }
  } finally {
    loading.value = false
  }
}

// 返回登录
const goToLogin = () => {
  router.push({ name: login })
}
</script>